import router from "@/router/index.ts";
import { RouteLocationNormalized, NavigationGuardNext } from "vue-router";
import { showNprogress, hiddenNprogress } from "@/utils/index.ts";
import { koiMsgWarning } from "@/utils/koi.ts";
// import { koiSessionStorage } from "@/utils/storage";
import useUserStore from "@/store/user/index.ts";
// import useRouteStore from "@/store/layout/routes.ts";
// 全局守卫：项目当中任意路由切换都会触发的钩子
// 全局前置守卫
// @ts-nocheck
router.beforeEach(
  (
    to: RouteLocationNormalized,
    from: RouteLocationNormalized,
    next: NavigationGuardNext,
  ) => {
    // to：你将要访问哪个路由，from: 你从哪个路由来，next: 路由放行
    console.log("前置守卫", to, from);
    const userStore = useUserStore();
    // const routeStore = useRouteStore();
    // const isLogin = koiSessionStorage.get("user");
    // 开启全屏动画
    showNprogress();
    console.log("isLogin",userStore.getToken)
    if (userStore.getToken) {
      // 登录成功，访问login，拒绝访问，指向首页
      if (to.path == "/login") {
        next({ path: "/home" });
      } else {

        // 用户登录，有token，判断是否有按钮数据，先获取用户信息和菜单权限数据，看看是否token有效
        // const hasRole = userStore.routeList;
        // if(hasRole.length > 0){
        //   next();
        // } else {
        //   try {
        //     // 获取用户信息
        //     // 生成动态路由
        //     routeStore.generateMenuRoutes(router, userStore.getUserId);
        //     // 等待路由全部挂载
        //     next({...to, replace: true});
        //   } catch (error) {
        //     sessionStorage.clear();
        //     next({path: '/login'})
        //   }
        // }

        next();
      }
    } else {
      // 用户未登录
      if (to.path == "/login") {
        next();
      } else {
        koiMsgWarning("账号身份已过期，请重新登录🌻");
        next({ path: "/login", query: { redirect: to.path } });
      }
    }
  },
);

// 全局后置守卫
router.afterEach(
  (to: RouteLocationNormalized, from: RouteLocationNormalized) => {
    console.log("后置守卫", to, from);
    // 开启全屏动画
    // 结束全屏动画
    hiddenNprogress();
    // 标题切换
    document.title = to.meta.title + "🌻" || "YU-ADMIN🌻";
  },
);
